package com.tan.kotlintest.threadsynchronized;

/*
 * Copyright (C) 2018 重庆一聊高科技有限公司
 * 版权所有
 *
 * 功能描述：测试synchronized关键字
 * 作者：txj
 * 创建时间：2018/9/5
 *
 * 修改人：
 * 修改描述：
 * 修改日期
 */
public class TestSynchronized {

    static class Work {

        /**
         * 普通方法的synchronized关键字锁的是当前类的一个实例对象
         * 如果有多个对象,那么相互不干扰
         */
        synchronized void startWork() {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + "   开始工作---------------");
            ThreadTool.sleep(1000);
            System.out.println(threadName + "   工作结束---------------");
        }

        /**
         * static静态方法的synchronized关键字,锁的是当前类的class对象
         * class对象在jvm虚拟机中有且只有一份
         * 所以这时锁是需要抢资源的
         */
        static synchronized void startStaticWork() {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + " static  开始工作---------------");
            ThreadTool.sleep(1000);
            System.out.println(threadName + " static  工作结束---------------");
        }

    }

    static class WorkRunnable implements Runnable {

        private Work work;

        WorkRunnable(Work work) {
            this.work = work;
        }

        @Override
        public void run() {
            //work.startWork();
            Work.startStaticWork();
        }
    }

    public static void main(String[] args) {
        Work work = new Work();
        Work work1 = new Work();
        WorkRunnable workRunnable = new WorkRunnable(work);
        WorkRunnable workRunnable1 = new WorkRunnable(work1);
        new Thread(workRunnable).start();
        new Thread(workRunnable).start();
        new Thread(workRunnable1).start();
    }

}
